<template>
  <div id="apply-list">
    <div class="top">
      <h2>申请收款/申请记录</h2>
      <div class="search-elements">
        <span>项目名称</span>
        <el-input v-model="pageQuery.projectName" placeholder="请输入项目名称" size="small" clearable></el-input>
        <el-select v-model="pageQuery.currentStatus" placeholder="请选择申请收款状态" clearable collapse-tags>
          <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value" v-show="item.value !== 4"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="clickQuery" size="small" :disabled="btnDisabled">搜索</el-button>
      </div>
    </div>

    <el-table :data="tableData" border>
      <el-table-column label="项目名称" prop="projectName" show-overflow-tooltip></el-table-column>
      <el-table-column label="项目负责人" prop="projectManager"></el-table-column>
      <el-table-column label="采购结算负责人" prop="contacts">
        <template slot-scope="scope">
          <div>{{ scope.row.clearingBuyer }}</div>
          <div>{{ scope.row.clearingBuyerPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="165"></el-table-column>
      <el-table-column label="申请金额(元)" prop="applyMoney"></el-table-column>
      <el-table-column label="收款方式" width="145">
        <template slot-scope="scope">{{ collectWayEnums[scope.row.collectWay] }}</template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">{{ formatStatus(scope.row) }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-popover v-if="[0, 1, 2, 3, 4, 5, 6, 7].includes(scope.row.currentStatus) && !['APPLY_COLLECT', 'SAVE', 'FIRST_AUDIT_REJECT', 'REAUDIT_REJECT_BUYER'].includes(scope.row.applyCollectStateEnum)" v-show="scope.row.currentStatus !== -1" style="margin: 0 5px" :open-delay="250" :close-delay="250" :disabled="openStatus" placement="top" trigger="hover">
            <p>功能升级中，暂不可用</p>
            <el-button v-if="openStatus" type="text" @click="handleViewOrMod(scope.row, 'view')" slot="reference">查看</el-button>
            <span v-else style="color: #c0c4cc" slot="reference">查看</span>
          </el-popover>
          <!--<el-button type="text" v-if="[0, 2, 4].includes(scope.row.currentStatus)" @click="handleViewOrMod(scope.row, 'mod')">修改信息</el-button>-->
          <!--<el-button type="text" v-if="scope.row.currentStatus !== 1 && scope.row.currentStatus !== 4" @click="handleView(scope.row)">查看</el-button>-->
          <!--<el-button type="text" v-if="scope.row.currentStatus === 0" @click="handleWithdraw(scope.row)">撤销申请</el-button>-->
          <!--<el-button type="text" v-if="scope.row.currentStatus === 1 || scope.row.currentStatus === 5" @click="handleMod(scope.row)">修改信息</el-button>-->
          <!--<el-button v-if="scope.row.currentStatus === 4" type="text" @click="handleReapply(scope.row)">重新申请</el-button>-->
          <!--<el-button v-if="scope.row.currentStatus === 4" type="text" @click="handleDeleteRecord(scope.row)">删除</el-button>-->
          <!-- 有按钮的状态 申请收款、待提交(去提交)、初审驳回(修改)、采购驳回供应商 -->
          <template v-if="scope.row.projectType != '0'">
            <el-popover style="margin: 0 5px" :open-delay="250" :close-delay="250" v-if="['APPLY_COLLECT', 'SAVE', 'FIRST_AUDIT_REJECT', 'REAUDIT_REJECT_BUYER'].includes(scope.row.applyCollectStateEnum)" v-show="scope.row.currentStatus !== -1" :disabled="openStatus" placement="top" trigger="hover">
              <p>功能升级中，暂不可用</p>
              <el-button v-if="openStatus" slot="reference" type="text" @click="applyCollect(scope.row)">{{ getBtnCn(scope.row) }}</el-button>
              <span style="color: #c0c4cc" v-else slot="reference">{{ getBtnCn(scope.row) }}</span>
            </el-popover>
            <!-- 有按钮的状态 用于供应商修改收款类型(即 重收款) 待提交(去提交)、初审驳回(修改)、采购驳回供应商 -->
            <el-popover style="margin: 0 5px" :open-delay="250" :close-delay="250" v-if="scope.row.ifCanReSubmit && ['SAVE', 'FIRST_AUDIT_REJECT', 'REAUDIT_REJECT_BUYER'].includes(scope.row.applyCollectStateEnum)" v-show="scope.row.currentStatus !== -1" :disabled="openStatus" placement="top" trigger="hover">
              <p>功能升级中，暂不可用</p>
              <el-button v-if="openStatus" slot="reference" type="text" @click="readyToReApplyCollect(scope.row)">重新申请收款</el-button>
              <span style="color: #c0c4cc" v-else slot="reference">重新申请收款</span>
            </el-popover>
          </template>
          <!-- 状态 初审中、复审中、复审通过、已打款 -->
          <!-- <span style="margin: 0 5px" v-else type="text">{{ getBtnCn(scope.row) }}</span> -->
          <!-- 按钮 查看记录 -->
          <!-- <el-popover style="margin: 0 5px" :open-delay="250" :close-delay="250" :disabled="openStatus" placement="top" trigger="hover">
            <p>功能升级中，暂不可用</p>
            <el-badge v-if="openStatus" slot="reference" is-dot :hidden="!['FIRST_AUDIT_REJECT', 'REAUDIT_REJECT_BUYER'].includes(scope.row.applyCollectStateEnum)">
              <el-button type="text" @click="handleViewHistory(scope.row)">查看记录</el-button>
            </el-badge>
            <span style="color: #c0c4cc" v-else slot="reference">查看记录</span>
          </el-popover> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="lowerFoot">
      <pagination :total="total" :page.sync="pageQuery.pageIndex" :limit.sync="pageQuery.pageSize" @pagination="getList" />
    </div>
    <!-- 采购二期申请收款 -->
    <el-dialog title="请选择收款方式及费用类型" :visible.sync="dialogApplyVisible" width="30%" :before-close="dialogApplyClose">
      <div style="margin-bottom: 10px">
        <b style="margin-right: 20px">收款方式:</b>
        <el-select size="small" clearable v-model="applyFormData.collectWay" @change="recieveTypeSel" :disabled="collectWayDisabled">
          <template v-if="realCollectWay * 1 === 4">
            <el-option label="据实结算" :value="4"></el-option>
          </template>
          <template v-else-if="currentRow.ifReApplyCollect">
            <template v-if="[0, 1, 4].includes(currentRow.collectWay)">
              <el-option label="一次性收款并结项" :value="0"></el-option>
              <el-option label="首次收款" :value="1"></el-option>
              <el-option label="据实结算" :value="4" v-show="realFeeType"></el-option>
            </template>
            <template v-else-if="[2, 3].includes(currentRow.collectWay)">
              <el-option label="阶段收款" :value="2"></el-option>
              <el-option label="尾款" :value="3"></el-option>
            </template>
            <template v-else></template>
          </template>
          <template v-else-if="!currentRow.applyCollectId">
            <el-option label="一次性收款并结项" :value="0"></el-option>
            <el-option label="首次收款" :value="1"></el-option>
            <el-option label="据实结算" :value="4" v-show="realFeeType"></el-option>
          </template>
          <template v-else>
            <el-option label="阶段收款" :value="2"></el-option>
            <el-option label="尾款" :value="3"></el-option>
          </template>
        </el-select>
      </div>
      <div style="margin-bottom: 10px">
        <b style="margin-right: 20px">费用类型:</b>
        <el-select size="small" clearable v-model="applyFormData.feeType" :disabled="selectDisabled">
          <el-option v-for="(type, index) in feeTypeEnums" :key="index" :label="type" :value="index"></el-option>
        </el-select>
      </div>

      <div class="explanation">
        <h2>请仔细阅读以下说明</h2>
        <p>
          如有
          <span class="money-type-color">一次性收款</span>
          ，直接选择“一次性收款并结项”
        </p>
        <p>
          如有
          <span class="money-type-color">两次收款</span>
          ，第一次选择“申请首次收款”，第二次选择“申请尾款”
        </p>
        <p>
          如有
          <span class="money-type-color">分三次及三次以上收款</span>
          ，第一次选择“申请首次收款”，中间付款选择“申请阶段收款”，最后一笔选择“申请尾款”
        </p>
        <p>
          <span class="money-type-color">据实结算</span>
          的收款方式仅支持费用类型是会议类，框架服务模式，按场次收款的项目，可多次申请
        </p>
        <p></p>
      </div>
      <div class="dialog-button">
        <el-button type="primary" @click="confirmApplyCollect">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCollectList, getCollectOpenStatus,fetchSettlementViewUrl } from '@/api/apply-collect.js'
import { withdrawApplyingReceivingMoney, deleteRecord } from '@/api/apply-money.js'
import { getFeeTypeCollectWayByBid } from '@/api/supplierFillApi'
import { collectWayEnums, currentStatusEnums, feeTypeEnums, applyCollectStateEnums } from '@/const/apply-collect'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import {xjdLogin} from "@/request/api";
import md5 from 'js-md5' // 局部MD5引用
export default {
  components: { Pagination },
  data() {
    return {
      statusOptions: currentStatusEnums.map((e, index) => {
        return {
          value: index,
          label: e.replace('(采购驳回)', '')
        }
      }),
      openStatus: false, // 申请收款 申请、修改、查看记录 按钮启用状态
      collectWayEnums,
      currentStatusEnums,
      feeTypeEnums,
      tableData: [],
      total: 0,
      pageQuery: {
        pageIndex: 1,
        pageSize: 10,
        projectName: '',
        currentStatus: ''
      },
      btnDisabled: false,
      dialogApplyVisible: false, // 申请收款 弹框
      applyFormData: {
        buyerInviteId: '', // 招标信息表id
        projectName: '',
        collectWay: '',
        feeType: '',
        lastId: ''
      },
      currentRow: {},
      selectDisabled: false,
      collectWayDisabled: false,
      realCollectWay: null,
      realFeeType: true,
      hasVal: false
    }
  },
  created() {
    this.initBtnsOpenStatus()
    this.getList()
  },
  computed: {
    ...mapGetters(['id'])
  },

  methods: {
    formatStatus(row) {
      return row.currentStatus === -1 ? '已终止，请联系结算负责人' : currentStatusEnums[row.currentStatus].replace('(采购驳回)', '')
    },
    recieveTypeSel(val) {
      if (val * 1 === 4) {
        this.applyFormData.feeType = 0
        this.selectDisabled = true
      } else {
        this.selectDisabled = false
      }
      if (this.hasVal) {
        this.selectDisabled = true
      }
    },
    getBtnCn(row) {
      const found = applyCollectStateEnums.find(item => item.en === row.applyCollectStateEnum)
      return found ? found.cn : ''
    },
    async initBtnsOpenStatus() {
      getCollectOpenStatus().then(res => {
        this.openStatus = res.data === 'Y' ? true : false
      })
    },
    getList() {
      this.btnDisabled = true
      getCollectList(this.pageQuery)
        .then(res => {
          this.total = res.data.total
          this.tableData = res.data.records
        })
        .finally(() => {
          this.btnDisabled = false
        })
    },
    clickQuery() {
      this.pageQuery.pageIndex = 1
      this.getList()
    },
    // 点击重新申请收款 弹框确认
    readyToReApplyCollect(row) {
      this.$confirm('重新申请收款，您提交的材料需要全部重新上传，请确认。', '重新申请收款', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // ifReApplyCollect 用于选项的判断 lastId 重新收款所需提供的上次的id
          this.applyCollect({ ...row, applyCollectStateEnum: 'APPLY_COLLECT', ifReApplyCollect: true, lastId: row.id })
        })
        .catch(() => {
          this.$message.info('已取消')
        })
    },
    applyCollect(row) {
      this.collectWayDisabled = false
      this.selectDisabled = false
      this.realFeeType = true
      this.hasVal = false
      this.applyFormData.buyerInviteId = row.buyerInviteId
      this.applyFormData.projectName = row.projectName
      this.applyFormData.totalPrice = row.totalPrice
      this.applyFormData.id = row.id // 最新的收款id
      this.applyFormData.lastId = row.lastId // 重新收款所需提供的上次的id
      getFeeTypeCollectWayByBid({
        buyerInviteBid: row.buyerInviteId,
        supplierId: this.id
      }).then(res => {
        if ([0, 1, 4].includes(res.data.collectWay * 1)) {
          this.collectWayDisabled = true
          this.realCollectWay = res.data.collectWay
          this.applyFormData.collectWay = res.data.collectWay
          this.recieveTypeSel(this.applyFormData.collectWay)
        }
        if ([0, 1].includes(res.data.feeType * 1)) {
          this.selectDisabled = true
          this.hasVal = true
          this.applyFormData.feeType = res.data.feeType
          if (res.data.feeType * 1 === 1) {
            this.realFeeType = false
          }
        }
      })
      if (row.applyCollectStateEnum === 'APPLY_COLLECT') {
        // 新增申请收款
        this.applyFormData.id = ''
        this.currentRow = row
        this.dialogApplyVisible = true
      } else {
        // 修改提交、驳回修改提交
        this.$router.push({
          // name: 'applyCollect',
          path: '/supplierCenter/apply-collect',
          query: {
            formType: 'mod',
            ...this.applyFormData
          }
        })
      }
    },
    dialogApplyClose(done) {
      for (const key in this.applyFormData) {
        this.applyFormData[key] = ''
      }
      done()
    },
    confirmApplyCollect() {
      if (this.applyFormData.collectWay.toString() === '') {
        this.$message.warning('请选择收款方式')
        return
      }
      if (this.applyFormData.feeType.toString() === '') {
        this.$message.warning('请选择费用类型')
        return
      }
      this.$router.push({
        // name: 'applyCollect', // TODO name 替换path
        path: '/supplierCenter/apply-collect',
        query: {
          formType: 'add',
          ...this.applyFormData,
          id: ''
        }
      })
    },
    handleViewHistory(row) {
      this.$router.push({
        name: 'applyHistory',
        query: {
          id: row.id,
          projectName: row.projectName
        }
      })
    },
    handleViewOrMod(row, formType) {
      if(row.projectType==='0'){
        // 医咻项目：跳转到外部结算单系统
        this.jumpToMedicalSettlement(row.id);
        return;
      }
      this.$router.push({
        path: '/supplierCenter/apply-collect',
        query: {
          id: row.id,
          formType
        }
      })
    },
    /**
     * 查看医咻项目的结算单 - 跳转到外部结算单页面
     */
    jumpToMedicalSettlement(orderId) {
        // 2. 生成时间戳
        const timestamp = Date.now().toString();

        // 3. 生成签名：MD5(orderId + timestamp + secretKey)
        const secretKey = 'wmzh'; // 抽到 config.js

        const sign = md5(orderId  + timestamp + secretKey);
        // 4. 请求后端获取查看链接
        const params = { orderId, timestamp, sign };
        fetchSettlementViewUrl(params).then(res => {
            const viewUrl = res.data;
            // 5. 在新标签页打开
            window.open(viewUrl, '_blank');
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '获取结算单链接失败，请稍后重试!'
          })
        })

    },



    handleDeleteRecord(row) {
      this.$confirm('确认删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRecord({
          id: row.id
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '删除失败，请重试!'
            })
          })
      })
    },
    handleWithdraw(row) {
      withdrawApplyingReceivingMoney({
        id: row.id
      }).then(() => {
        this.msgSuccess('撤销成功')
        this.getList()
      })
    },
    handleReapply(row) {
      this.$router.push({
        path: '/supplierCenter/apply-money',
        query: {
          receivingMoneyId: row.id.toString(),
          formType: '2'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
#apply-list {
  padding: 10px 20px;
  .top {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
  }
  .search-elements {
    margin-left: 20px;
    span {
      font-size: 14px;
    }
    .el-input {
      width: 200px;
      margin: 0 10px;
    }
  }
  .lowerFoot {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}

.explanation {
  padding: 30px 18px 30px 18px;
  background-color: #f6cdbb;
  color: #000;

  h2 {
    margin-bottom: 20px;
  }

  p {
    margin-bottom: 5px;
  }
}

.money-type-color {
  color: red;
}

.dialog-button {
  margin-top: 20px;
  text-align: center;
}
::v-deep .el-select {
  margin-right: 10px;
}
::v-deep .el-select .el-input .el-input__inner {
  height: 32px;
}
::v-deep .el-input__icon {
  line-height: 32px;
}
</style>
